<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\Course;
use App\Models\Order;
use App\Models\User;
use App\Models\Vip;
use App\Models\VipUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Overtrue\LaravelWeChat\Facade as WeChat;

class WechatPayController extends Controller
{
    public function index(Request $Request)
    {
        $type = $Request->type;
        $product = Course::where('id',$Request->id)->where('status',1)->first();

        if(!$product){
            return response()->json(['code' => '404', 'msg' => '商品已下架']);
        }

        $user = Auth::user();
        //判断是否购买过
        $is = Order::where('user_id',$user->id)->where('product_id',$Request->id)->where('type',$Request->type)->where('pay_status','success')->first();
        if($is){
            return response()->json(['code' => '500', 'msg' => '此商品已经购买过了']);
        }

        $integral = 0;
        $amount = 0;
        $coupon = 0;//优惠券ID
        $payment_method = 'wechat';
        $pay_status = 'afoot';
        $price = $product->price;
        $body = $product->title.'的订单：';
        $no = 'NO'.uniqid();
        //生成订单
        $order = new Order();
        $order->no = $no;
        $order->title = $body;
        $order->type = $type;
        $order->user_id = $user->id;
        $order->product_id = $Request->id;
        $order->product_sku_id = 0;
        $order->amount = $amount;
        $order->coupon = $coupon;
        $order->address = '';
        $order->integral = $integral;
        $order->total_amount = $price;
        $order->pay_amount = 0;//实际支付金额
        $order->pay_status = $pay_status;
        $order->paid_at = null;
        $order->payment_method = $payment_method;
        $order->payment_no = '';
        $order->extra = '';
        $order->closed = 0;

        $order->save();
        $openid = $user->openid;

        $payment = WeChat::payment(); // 初始化支付实例

        try {
            // 创建预支付订单
            $result = $payment->order->unify([
                'body' => $body,
                'out_trade_no' => $no,
                'total_fee' => $order->total_amount * 100,
                'trade_type' => 'JSAPI',
                'openid' => $openid,
                'notify_url' => config('wechat.payment.default.notify_url'),
            ]);
            // 生成前端调起支付的参数
            $payParams = $payment->jssdk->bridgeConfig($result['prepay_id']);

            return response()->json(['code' => 200, 'message' => '操作成功','no'=>$no,'data'=>$payParams]);
        } catch (\Exception $e) {
            return response()->json(['code' => 500, 'message' => $e->getMessage()]);
        }
    }


    public function vip(Request $Request)
    {
        $product = Vip::where('id',$Request->id)->where('status',1)->first();

        if(!$product){
            return response()->json(['code' => '404', 'msg' => '商品已下架']);
        }




        $user = Auth::user();
        //判断是否购买过
        $is = Order::where('user_id',$user->id)->where('type','vip')->where('pay_status','success')->first();
        if($is){
            //续费
        }


        $price = $product->price;
        $coupon = 0;//优惠券ID
        if($Request->coupon_id){
            $iscoupon = Coupon::where('id',$Request->coupon_id)->where('status',1)->first();
            if($iscoupon){
                $price = $product->price - $iscoupon->amount;
                $coupon = $iscoupon->id;//优惠券ID
            }
        }

        $integral = 0;
        $amount = 0;

        $payment_method = 'wechat';
        $pay_status = 'afoot';
        $body = 'VIP订单 ';

        $no = 'NO-VIP'.uniqid();
        //生成订单
        $order = new Order();
        $order->no = $no;
        $order->title = $body;
        $order->type = 'vip';
        $order->user_id = $user->id;
        $order->product_id = $Request->id;
        $order->product_sku_id = 0;
        $order->amount = $amount;
        $order->coupon = $coupon;
        $order->address = '';
        $order->integral = $integral;
        $order->total_amount = $price;
        $order->pay_amount = 0;//实际支付金额
        $order->pay_status = $pay_status;
        $order->paid_at = null;
        $order->payment_method = $payment_method;
        $order->payment_no = '';
        $order->extra = '';
        $order->closed = 0;

        $order->save();
        $openid = $user->openid;

        $payment = WeChat::payment(); // 初始化支付实例

        try {
            // 创建预支付订单
            $result = $payment->order->unify([
                'body' => $body,
                'out_trade_no' => $no,
                'total_fee' => $order->total_amount * 100,
                'trade_type' => 'JSAPI',
                'openid' => $openid,
                'notify_url' => config('wechat.payment.default.notify_url'),
            ]);
            // 生成前端调起支付的参数
            $payParams = $payment->jssdk->bridgeConfig($result['prepay_id']);

            return response()->json(['code' => 200, 'message' => '操作成功','no'=>$no,'data'=>$payParams]);
        } catch (\Exception $e) {
            return response()->json(['code' => 500, 'message' => $e->getMessage()]);
        }
    }

    public function ispay(Request $Request)
    {
        if(!$Request->no){
            return response()->json(['code' => '500', 'msg' => '参数错误']);
        }
        $is = Order::where('no',$Request->no)->where('pay_status','success')->first();
        if(!$is){
            return response()->json(['code' => '200', 'data' => false]);
        }
        return response()->json(['code' => '200', 'data' => true]);
    }

    public function wechatNotify(Request $request)
    {
        $payment = WeChat::payment();
        $response = $payment->handlePaidNotify(function ($message, $fail) {
            // $message 为微信支付回调的参数数组
            $orderNo = $message['out_trade_no']; // 商户订单号
            $totalFee = $message['total_fee']; // 支付金额（分）

            // 1. 验证订单是否存在
            $order = Order::where('no', $orderNo)->first();
            if (!$order) {
                return $fail('订单不存在');
            }

            // 2. 验证支付金额是否一致
            if ($order->total_amount != ($totalFee / 100)) {
                return $fail('支付金额不匹配');
            }

            // 3. 验证支付状态
            if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') {
                // 支付成功：更新订单状态
                $order->paid_at = Date('Y-m-d H:i:s',time());
                $order->payment_no = $message['transaction_id']; // 微信支付订单号
                $order->pay_status = 'success';
                $order->pay_amount = $totalFee / 100;
                $order->extra = json_encode($message);

                $data = DB::transaction(function () use ($order) {
                    $order->save();
                    if($order->type == 'vip'){
                        $vip = Vip::find($order->product_id);
                        $duration = $vip->duration*60*60*24;
                        $time = time();
                        //判断是否存在
                        $vipuser = VipUser::where('user_id',$order->user_id)->where('vip_id',$vip->id)->first();
                        if(!$vipuser){
                            $vipuser = new VipUser();
                            $vipuser->user_id = $order->user_id;
                            $vipuser->vip_id = $vip->id;
                            $vipuser->start_date = Date('Y-m-d',$time);
                            $vipuser->end_date = Date('Y-m-d',$duration);
                            $vipuser->save();
                        }else{
                            $t = strtotime($vipuser->end_date);
                            $vipuser->end_date = Date('Y-m-d',$time+$duration);
                            if($t > $time){
                                $vipuser->end_date = Date('Y-m-d',$t+$duration);
                            }
                            $vipuser->vip_id = $vip->id;
                            $vipuser->save();
                        }
                    }
                    return true;
                });
                // 可在此处触发其他业务逻辑（如发货、积分增加等）
                return true; // 告诉微信“处理成功”
            }

            // 支付失败
            return $fail('支付失败');
        });

        return $response; // 返回微信要求的XML格式响应
    }
}